<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <!-- <a-form layout="inline" :colon="false">
          <a-row :gutter="48">
            <a-col :md="4" :sm="24">
              筛选条件
              <a-switch @change="toggleAdvanced" />
            </a-col>
            <a-col :md="10" :sm="24">
              <a-form-item>
                <a-input-group compact>
                  <a-select v-model="queryParam.dateType" style="width: 30%">
                    <a-select-option value="create">下单时间</a-select-option>
                    <a-select-option value="payment">支付时间</a-select-option>
                    <a-select-option value="delivery">发货时间</a-select-option>
                  </a-select>
                  <a-range-picker
                    v-model="queryParam.date"
                    style="width: 70%"
                    show-time
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :ranges="{
                      '今天': [moment().startOf('day'), moment().endOf('day')],
                      '昨天': [moment().add(-1, 'days').startOf('day'), moment().add(-1, 'days').endOf('day')],
                      '最近7天': [moment().add(-6, 'days').startOf('day'), moment().endOf('day')],
                      '最近30天': [moment().add(-29, 'days').startOf('day'), moment().endOf('day')],
                      '这个月': [moment().startOf('month'), moment().endOf('month')],
                      '上个月': [moment().add(-1, 'month').startOf('month'), moment().add(-1, 'month').endOf('month')],
                    }"
                  />
                </a-input-group>
              </a-form-item>
            </a-col>
            <a-col :md="10" :sm="24">
              <a-form-item>
                <a-input-group compact>
                  <a-select v-model="queryParam.searchType" style="width: 30%">
                    <a-select-option value="1">订单编号</a-select-option>
                    <a-select-option value="2">商品名称</a-select-option>
                    <a-select-option value="3">商品编号</a-select-option>
                    <a-select-option value="4">客户昵称</a-select-option>
                    <a-select-option value="5">收货人姓名</a-select-option>
                    <a-select-option value="6">收货人手机</a-select-option>
                    <a-select-option value="7">支付单号</a-select-option>
                    <a-select-option value="8">提货码</a-select-option>
                    <a-select-option value="9">自提点名称</a-select-option>
                  </a-select>
                  <a-input-search
                    v-model="queryParam.keyword"
                    style="width: 70%;top: 0"
                    placeholder
                    enter-button
                  />
                </a-input-group>
              </a-form-item>
            </a-col>
            <a-col :md=" 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="advanced && { overflow: 'hidden' } || {} "
              >
                <a-button disabled>批量标记</a-button>
                <a-button style="margin-left: 8px">订单导出</a-button>
              </span>
            </a-col>
            <template v-if="advanced">
              <a-col v-for="(f,i) in filterData" :key="i" :md="24" :sm="24">
                <a-form-item v-model="queryParam.filterObj" :label="f.label">
                  <a-button
                    :class="'filterBtn' + (f.active ? ' active' : '')"
                    @click="toggleFilter(i,undefined,f,$event)"
                  >不限</a-button>
                  <a-button
                    v-for="(o,index) in f.option"
                    :key="o.filed"
                    style="margin-left: 8px"
                    :class="'filterBtn' + (o.active ? ' active' : '')"
                    @click="toggleFilter(i,index,o,$event)"
                  >{{ o.label }}</a-button>
                </a-form-item>
              </a-col>
              <a-col :md="24" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  :style="advanced && { overflow: 'hidden' } || {} "
                >
                  <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                </span>
              </a-col>
            </template>
          </a-row>
        </a-form> -->
        <Form />
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1">
              <a-icon type="delete" />删除
            </a-menu-item>
            <!-- lock | unlock -->
            <a-menu-item key="2">
              <a-icon type="lock" />锁定
            </a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <s-table
        ref="table"
        size="default"
        row-key="key"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :row-selection="rowSelection"
        show-pagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">配置</a>
            <a-divider type="vertical" />
            <a @click="handleSub(record)">订阅报警</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <!-- <SForm :form="form" layout="inline" :form-items="formItems" :colon="false" /> -->

      <!-- <SSelect :options="dateOptions" default-value="create" /> -->
      <!-- <TagCheckbox :options="filterData[0].option" /> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis, SForm, SSelect, SDatePicker, TagCheckbox } from '@/components'
import { getRoleList, getServiceList } from '@/api/manage'

import CreateForm from './modules/CreateForm'
import TagCheckboxList from './modules/TagCheckboxList'
import Form from './modules/Form'

const columns = [
  {
    title: '#',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '订单编号',
    dataIndex: 'no'
  },
  {
    title: '商品信息',
    dataIndex: 'description',
    scopedSlots: { customRender: 'description' }
  },
  {
    title: '实收金额',
    dataIndex: 'callNo',
    sorter: true,
    needTotal: true,
    customRender: text => '￥' + text
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    sorter: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: 'default',
    text: '已取消'
  },
  1: {
    status: 'processing',
    text: '待支付'
  },
  2: {
    status: 'success',
    text: '已完成'
  },
  3: {
    status: 'error',
    text: '异常'
  },
  4: {
    status: '',
    text: '待发货'
  },
  5: {
    status: '',
    text: '已发货'
  }
}

export default {
  name: 'TableList',
  components: {
    Form,
    TagCheckboxList,
    TagCheckbox,
    SDatePicker,
    SSelect,
    SForm,
    STable,
    Ellipsis,
    CreateForm
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    }
  },
  data() {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        dateType: 'create',
        searchType: '1',
        filterObj: {}
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getServiceList(requestParameters).then(res => {
          return res.result
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      filterObj: {}
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  created() {
    getRoleList({ t: new Date() })
  },
  methods: {
    moment: moment,
    reset() {
      this.queryParam.filterObj = {}
      this.filterData.forEach(item => {
        item.active = true
        item.option.forEach(optionItem => {
          optionItem.active = false
        })
      })
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('修改成功')
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('新增成功')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
      console.log(this.advanced)
    },
    toggleFilter(filterIndex, optionIndex, currentItem, e) {
      console.log(filterIndex, optionIndex, currentItem, e)
      // this.queryParam = this.queryParam || {}
      // this.queryParam[filterIndex] = []
      console.log(this.filterData)
      // this.filterData = this.filterData.map((item, index) => {
      //   const res = item
      //   if (index === filterIndex) {
      //     res.active = true
      //     res.option.forEach((iitem, iindex) => {
      //       if (optionIndex === undefined) {
      //         iitem.active = false
      //         return
      //       }
      //       if (optionIndex === iindex) {
      //         iitem.active = !iitem.active
      //       }
      //       if (iitem.active) {
      //         res.active = false
      //       }
      //       // return iitem
      //     })
      //   }
      //   return res
      // })
      // if (optionIndex !== undefined) {
      //   // this.filterData[filterIndex].option[optionIndex].active = !this.filterData[filterIndex].option[optionIndex]
      //   //   .active
      //   data[filterIndex].active = true
      //   data[filterIndex].option.forEach((item, index) => {
      //     if (optionIndex === index) {
      //       item.active = true
      //     }
      //     if (item.active) {
      //       data[filterIndex].active = false
      //       // this.queryParam[filterIndex].push(item.field)
      //     }
      //   })
      // } else {
      //   data[filterIndex].active = !data[filterIndex].active
      //   data[filterIndex].option.forEach(item => {
      //     item.active = false
      //   })
      // }
      console.log(this.filterData)
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang="less">
.filterBtn.ant-btn:focus {
  color: rgba(0, 0, 0, 0.65);
  border-color: #d9d9d9;
}
.filterBtn.ant-btn.active,
.filterBtn.ant-btn:hover {
  color: #40a9ff;
  border-color: #40a9ff;
}
.form-wrapper {
  .ant-input-group.ant-input-group-compact {
    .ant-form-item-control-wrapper {
      display: block;
    }
  }
}
</style>
